package com.cn.zpark;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * ServletContext实现Servlet数据交换
 * 统计网站浏览次数
 */
@WebServlet(value = "/scd3.do", loadOnStartup = 0)
public class ServletContextDemo03 extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取context对象
        ServletContext context = request.getServletContext();
        // 通过Context对象获取绑定数据
        Object count = context.getAttribute("count");
        // 将对象类型转为integer类型
        Integer number = (Integer) count;
        // +1
        ++ number;
        // 将修改之后的数据绑定到context对象中
        context.setAttribute("count", number);
        // 将信息响应到浏览器
        response.setContentType("text/html;charset=utf-8"); // 设置响应格式
        // 获取写出对象流
        PrintWriter writer = response.getWriter();
        writer.println("<h1>该网站被浏览的次数为： " + number + "次</h1>");
        writer.close();
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        // 获取context对象
        ServletContext context = config.getServletContext();
        // 绑定Servlet交互数据
        context.setAttribute("count", 0);

    }
}
